﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace ProTrack.Utility
{
    public class MD5Helper
    {
        public static string GetMd5EnCode(string content)
        {
            // 创建一个MD5对象
            using (MD5 md5 = MD5.Create())
            {
                // 将输入字符串转换为字节数组
                byte[] inputBytes = Encoding.UTF8.GetBytes(content);
                // 计算输入字节数组的哈希值
                byte[] hashBytes = md5.ComputeHash(inputBytes);
                // 将字节数组转换为字符串
                StringBuilder hashString = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    hashString.AppendFormat("{0:x2}", b);
                }
                return hashString.ToString();
            }
        }


        /// <summary>
        /// HMACSHA256 转十六进制
        /// </summary>
        /// <param name="content"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string HmacSHA256(string content, string secret)
        {
            using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(content));

                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashmessage.Length; i++)
                {
                    builder.Append(hashmessage[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }
        /// <summary>
        /// HMACSHA256
        /// </summary>
        /// <param name="content"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string CalcHMACSHA256Hash(string content, string key)
        {
            StringBuilder builder = new StringBuilder();
            var enc = Encoding.Default;
            HMACSHA256 hasher = new HMACSHA256(enc.GetBytes(key));
            byte[] baHashedText = hasher.ComputeHash(enc.GetBytes(content));
            for (int i = 0; i < baHashedText.Length; i++)
            {
                builder.Append(baHashedText[i]);
            }
            return builder.ToString();
        }

    }
}
